import json
import urllib.parse
import time
from urllib import parse
import excelUtil

xhsHttp = 'https://www.xiaohongshu.com/'

def xhsSearch(flow):
    httpStart = 'https://www.xiaohongshu.com/api/sns/v3/search/user?keyword'
    # httpStart = 'https://www.xiaohongshu.com/api/sns/v4/search/notes/recommend_info?'
    if flow.request.url.startswith(httpStart):
        keyword = parse.unquote(urllib.parse.urlparse(flow.request.url).query.split('&')[0].replace('keyword=', ''))
        print(flow.response.text)
        print('=========================================' + keyword)
        text = json.loads(flow.response.text)
        resultData = [[keyword]]
        if text != 'null':
            users = text.get('data').get('users')
            if (len(users) > 0):
                firstUser = users[0]
                # print(keyword)
                # print(firstUser)
                userName = firstUser.get('name')
                userId = firstUser.get('id')
                if firstUser.get('desc').startswith('企业'):
                    isOrg = '是' if firstUser.get('desc').startswith('企业') else '否'
                    # https://www.xiaohongshu.com/user/profile/557e8ed8a75c951194e8f9e9?xhsshare=CopyLink&appuid=5ead3b15000000000100040c&apptime=1588511104
                    shareUrl = 'https://www.xiaohongshu.com/user/profile/' + userId + '?xhsshare=CopyLink&appuid=5ead3b15000000000100040c&apptime=%d' % (int(time.time()))
                    if excelUtil.isContains(userName, keyword):
                        resultData[0] = [keyword, userName, shareUrl, isOrg]
        excelUtil.write_excel_xls_append(excelUtil.FILE_PATH, '小红书', resultData)